package controller

import (
	"github.com/gin-gonic/gin"

	"shorten/internal/service"
	"shorten/pkg/app"
	"shorten/pkg/errcode"
	"shorten/pkg/setting"
)

// 登录
func (b *base) Login(c *gin.Context) {
	//1 参数绑定
	var param service.LoginParam
	code, msg := service.BindAndValid(c, &param)
	if code > 0 {
		app.FailedWithMsg(c, code, msg)
		return
	}
	//2 参数合法性校验
	svc := service.New(c.Request.Context())
	userId, err := svc.CheckUserPwd(param.UserName, param.Password)
	if err != nil {
		app.FailedWithMsg(c, errcode.UserLoginFailed, err.Error())
		return
	}
	//3 生成jwt token
	token, err := app.GenToken(userId, setting.Settings.Jwt)
	if err != nil {
		app.Failed(c, errcode.TokenCreateFailed)
		return
	}
	//4 返回生成的token
	app.Success(c, gin.H{
		"token": token,
	})
}

// 注册
func (b *base) Register(c *gin.Context) {
	//1 参数绑定
	var param service.RegisterParam
	code, msg := service.BindAndValid(c, &param)
	if code > 0 {
		app.FailedWithMsg(c, code, msg)
		return
	}
	//2 用户名是否存在
	svc := service.New(c.Request.Context())
	err := svc.CheckUser(param.UserName)
	if err != nil {
		app.Failed(c, errcode.UserExist)
		return
	}
	//3 新建用户
	err = svc.NewUser(&param)
	if err != nil {
		app.Failed(c, errcode.UserCreatedFailed)
		return
	}
	//4 返回成功标识
	app.Success(c, gin.H{})
}

func (b *base) Miss(c *gin.Context) {
	app.Failed(c, errcode.RouteNotFound)
	return
}

func (b *base) HomePage(c *gin.Context) {
	app.Success(c, gin.H{
		"msg": "home page",
	})
	return
}
